﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Client;

namespace McTools.Xrm.Connection.WinForms
{
    /// <summary>
    /// Formulaire de sélection d'une connexion à un serveur
    /// Crm dans une liste de connexions existantes.
    /// </summary>
    public partial class ConnectionSelector : Form
    {
        #region Variables

        /// <summary>
        /// Connexion sélectionnée
        /// </summary>
        ConnectionDetail selectedConnection;

        /// <summary>
        /// Obtient la connexion sélectionnée
        /// </summary>
        public ConnectionDetail SelectedConnection
        {
            get { return selectedConnection; }
        }

        private bool hadCreatedNewConnection;

        public CrmConnections ConnectionList { get; set; }

        private readonly ConnectionManager connectionManager;

        #endregion

        #region Constructeur

        /// <summary>
        /// Créé une nouvelle instance de la classe ConnectionSelector
        /// </summary>
        /// <param name="connections">Liste des connexions disponibles</param>
        /// <param name="cManager">Gestionnaire des connexions</param>
        public ConnectionSelector(CrmConnections connections, ConnectionManager cManager)
        {
            InitializeComponent();
            connectionManager = cManager;
            connections.Connections.Sort();

            LoadImages();

            foreach (ConnectionDetail detail in connections.Connections)
            {
                string groupName = String.Empty;

                switch (detail.AuthType)
                {
                    case AuthenticationProviderType.ActiveDirectory:
                        groupName = "OnPremise";
                        break;
                    case AuthenticationProviderType.OnlineFederation:
                        groupName = "CRM Online - Office 365";
                        break;
                    case AuthenticationProviderType.LiveId:
                        groupName = "CRM Online - CTP";
                        break;
                    case AuthenticationProviderType.Federation:
                        groupName = "Claims authentication - Internet Facing Deployment";
                        break;
                }

                var group = lvConnections.Groups.Cast<ListViewGroup>().FirstOrDefault(g => g.Name == groupName);
                if (group == null)
                {
                    group = new ListViewGroup(groupName, groupName);
                    lvConnections.Groups.Add(group);
                }

                var item = new ListViewItem(detail.ConnectionName);
                item.SubItems.Add(detail.Organization);
                item.SubItems.Add(detail.ServerName);
                item.SubItems.Add(detail.OrganizationVersion);
                item.Tag = detail;
                item.Group = group;

                if (detail.UseOnline)
                {
                    item.ImageIndex = 2;
                }
                else if (detail.UseOsdp)
                {
                    item.ImageIndex = 2;
                }
                else if (detail.UseIfd)
                {
                    item.ImageIndex = 1;
                }
                else
                {
                    item.ImageIndex = 0;
                }

                lvConnections.Items.Add(item);
            }

            var groups = new ListViewGroup[lvConnections.Groups.Count];

            lvConnections.Groups.CopyTo(groups, 0);

            Array.Sort(groups, new GroupComparer());

            lvConnections.BeginUpdate();
            lvConnections.Groups.Clear();
            lvConnections.Groups.AddRange(groups);
            lvConnections.EndUpdate();
        }

        private void LoadImages()
        {
            lvConnections.SmallImageList = new ImageList();
            lvConnections.SmallImageList.Images.Add(RessourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.server.png"));
            lvConnections.SmallImageList.Images.Add(RessourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.server_key.png"));
            lvConnections.SmallImageList.Images.Add(RessourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.CRMOnlineLive_16.png"));
          }

        #endregion

        #region Properties

        public bool HadCreatedNewConnection
        {
            get { return hadCreatedNewConnection; }
        }

        #endregion

        #region Méthodes

        private void BtnNewConnectionClick(object sender, EventArgs e)
        {
            var cForm = new ConnectionForm(true)
                            {
                                ConnectionList = ConnectionList,
                                StartPosition = FormStartPosition.CenterParent
                            };

            if (cForm.ShowDialog(this) == DialogResult.OK)
            {
                selectedConnection = cForm.CrmConnectionDetail;
                hadCreatedNewConnection = true;

                var item = new ListViewItem(selectedConnection.ConnectionName);
                item.SubItems.Add(selectedConnection.ServerName);
                item.SubItems.Add(selectedConnection.Organization);
                item.Tag = selectedConnection;

                lvConnections.Items.Add(item);
                lvConnections.SelectedItems.Clear();
                item.Selected = true;

                BValidateClick(sender, e);
            }
        }

        private void BtnDeleteClick(object sender, EventArgs e)
        {
            if (lvConnections.SelectedItems.Count > 0)
            {
                connectionManager.ConnectionsList.Connections.Remove((ConnectionDetail)lvConnections.SelectedItems[0].Tag);
                connectionManager.SaveConnectionsFile(ConnectionList);

                lvConnections.Items.Remove(lvConnections.SelectedItems[0]);
            }
        }

        private void LvConnectionsMouseDoubleClick(object sender, MouseEventArgs e)
        {
            BValidateClick(sender, e);
        }
        
        private void BValidateClick(object sender, EventArgs e)
        {
            if (lvConnections.SelectedItems.Count == 1)
            {
                selectedConnection = lvConnections.SelectedItems[0].Tag as ConnectionDetail;

                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void BCancelClick(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void LvConnectionsColumnClick(object sender, ColumnClickEventArgs e)
        {
            lvConnections.Sorting = lvConnections.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            lvConnections.ListViewItemSorter = new ListViewItemComparer(e.Column, lvConnections.Sorting);
        }

        #endregion
    }
}